<?php

namespace App\Http\Middleware;

use Closure;

class PageViewMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $create['ip'] = getIp();
        if ($create['ip'] == '127.0.0.1') {
            return $next($request);
        }

        $tmpIpInfo = json_decode(file_get_contents('http://api.map.baidu.com/location/ip?ip=' . $create['ip'] . '&ak=' . config('app.baidu_map_key')), true);
        if (!empty($tmpIpInfo['content'])) {
            $create['address'] = $tmpIpInfo['content']['address'];
        }

        $create['url'] = $request->url();

        $count = \App\PageView::where($create)
            ->where('created_at', '>', date('Y-m-d H:i:s', time() - 60))
            ->count();
        if ($count > 60) {
            abort(404);
        } else {
            $create['method'] = $request->method();
            $create['parameter'] = json_encode($request->all());

            //判定是否为外部来源
            if (!empty($_SERVER['HTTP_REFERER'])) {
                foreach (config('app.http_referer') as $name => $value) {
                    if (strpos($_SERVER['HTTP_REFERER'], $value['url']) !== false) {
                        $create['http_referer_name'] = $name;
                        //因无法获取关键词 此功能取消
//                        //得到超链接数组
//                        $urlArray = explode('?', $_SERVER['HTTP_REFERER']);
//                        //得到参数字符串
//                        $tmpParameter = $urlArray[1];
//                        //得到参数数组
//                        parse_str($tmpParameter, $parameter);
//                        $create['http_referer_q'] = $parameter[$value['key']];
                    }
                }
            }

            \App\PageView::create($create);
        }

        return $next($request);
    }
}
